package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.admin.service.AdUserService;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * @author Lenovo
 * @description 针对表【ad_user(管理员用户信息表)】的数据库操作Service实现
 * @createDate 2024-12-03 22:10:59
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser>
        implements AdUserService {

    /**
     * 用户登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto dto) {
        //1.校验参数
        if (dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.比对密码
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery()
                .eq(AdUser::getName, dto.getName()));
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String salt = adUser.getSalt();
        String password = dto.getPassword();
        String pwd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if (!pwd.equals(adUser.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //3.返回数据
        HashMap<String, Object> map = new HashMap<>();
        //生成token
        String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));
        map.put("token", token);
        adUser.setSalt("");
        adUser.setPassword("");
        map.put("user", adUser);
        return ResponseResult.okResult(map);
    }
}




